<?php
class TeamNetworkPage extends MemberPage {

    private static $db = array(
    );

    private static $has_one = array(
    );

}
class TeamNetworkPage_Controller extends MemberPage_Controller {

    /**
     * An array of actions that can be accessed via a request. Each array element should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this action
     *     'action' => '->checkAction' // you can only access this action if $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = array (
    	'Form',
        'member_detail',
        'build_tree',
        'placement_signup'
    );

    public function init() {
        parent::init();
    }
	
	function index(){
		Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('network/javascript/lang');
    	Requirements::javascript("network/javascript/TeamNetworkPage.min.js");
    	Requirements::css("network/css/TeamNetworkPage.css");
		return $this->renderWith(array('TeamNetworkPage_index', 'TeamNetworkPage', 'MemberPage', 'MemberOverviewPage', 'MemberAreaPage', 'Page', 'Controller'));
	}

    function doValidate($username){
        $id = (int)Distributor::get_id_by_username($username);
        $left = 0;
        $right = 0;
        $placement = DataObject::get_one('Placement', "MemberID = ".(int)$this->CurrentMember()->ID);
        if($placement){
            $left = (int)$placement->NLeft;
            $right = (int)$placement->NRight;
        }
        
        $count = Placement::get()->filter('NLeft:GreaterThanOrEqual', $left)->filter('NRight:LessThanOrEqual', $right)->filter('ID', $id)->count();
        return ($count) ? true : false;
    }

    function build_tree(){
        $username = $this->request->param('ID');
        if(!$this->doValidate($username)){
            return Convert::array2json(array('error' => _t('TeamNetworkPage.UNABLE_FIND_TEAM_NETWORK', 'Unable find team network for member username - {username}', '', array('username' => $username))));
        }
        
        $id = (int)Distributor::get_id_by_username($username);
        $left = 0;
        $right = 0;
        $placement = DataObject::get_one('Placement', "MemberID = ".(int)$this->CurrentMember()->ID);
        if($placement){
            $left = (int)$placement->NLeft;
            $right = (int)$placement->NRight;
        }

        $data = Placement::get()
        ->filter('NLeft:GreaterThanOrEqual', $left)
        ->filter('NRight:LessThanOrEqual', $right)
        ->find('ID', $id);

        $level = (int)$data->NLevel;
        $left = (int)$data->NLeft;
        $right = (int)$data->NRight;
        $parentid = (int)$data->ParentID;
        $parentusername = ($data->ParentID) ? $data->Parent()->Member()->Username : '';
        $position = (int)$data->NSeqno;
        $showlevel = Placement::get_show_level();
        $maxLevel = $level + $showlevel;
        
        $items = Placement::get()
        ->filter('NLeft:GreaterThanOrEqual', $left)
        ->filter('NRight:LessThanOrEqual', $right)
        ->filter('NLevel:LessThanOrEqual', $maxLevel)
        ->sort(array('NLevel' => 'ASC', 'NSeqno' => 'ASC', 'ID' => 'ASC'));

        $searchResult = array();
        if($items->count()){
            foreach($items as $key => $item){
                if($item->MemberID){
                    $member = $item->Member();
                    $arr_data = array();
                    $arr_data['id'] = $item->ID;
                    $arr_data['level'] = (int)($item->NLevel - $level);
                    $arr_data['parentid'] = (int)$item->ParentID;
                    $arr_data['position'] = (int)$item->NSeqno;
                    $arr_data['distributorid'] = (int)$member->ID;
                    $arr_data['rankcode'] = $member->RankCode;
                    $arr_data['username'] = ($member->Username) ? $member->Username : 'n/a';
					$arr_data['left'] = DBField::create_field('Int', $member->TodayTotalLeftGroupBV)->Formatted();
					$arr_data['right'] = DBField::create_field('Int', $member->TodayTotalRightGroupBV)->Formatted();
                    if(isset($searchResult[$arr_data['level']][$arr_data['parentid']][$arr_data['position']])){
                        continue;
                    }
                    
                    $searchResult[$arr_data['level']][$arr_data['parentid']][$arr_data['position']] = $arr_data;
                }
            }
        }

        $currentcol = 1;
        $child_limit = Placement::get_direct_child_limit();
        $totalcol = 1;
        for ($k = 1; $k < $showlevel; $k++) {
            $totalcol *= $child_limit;
        }
        $table = '';
        $arr_postparentid = array();
        $disabled = '';
        $currentusername = $this->CurrentMember()->Username;
        $currentmemberid = $this->CurrentMember()->ID;
        $currentmemberrankcode = $this->CurrentMember()->RankCode;
		$currentleft = DBField::create_field('Int', $this->CurrentMember()->TodayTotalLeftGroupBV)->Formatted();
		$currentright = DBField::create_field('Int', $this->CurrentMember()->TodayTotalRightGroupBV)->Formatted();
        
        if($username == $currentusername){
            $disabled = "disabled";
            $parentusername = "";
        }
        $table .= '<p><a href="#" rel="tooltip" title="'._t('TeamNetworkPage.VIEW_PREVIOUS_LEVEL', 'View previous level of team network').'" id="previous" data-username="'.$parentusername.'" class="btn action '.$disabled.'">'._t('TeamNetworkPage.PREVIOUS_LEVEL', 'Previous Level').'</a></p>';
        $table .= '<div class="team-table table-responsive">';
        $table .= '<table width="100%" class="table table-striped">';
        $table .= '<tbody>';
        if($username != $currentusername){
            $table .= '<tr>';
            $table .= '<td colspan="'.$totalcol.'" class="text-center">';
			$table .= '<a class="view_tree" href="#" data-username="'.$currentusername.'"><span class="glyphicon glyphicon-chevron-up"></span></a>';
            $table .= '<div><b>'._t('TeamNetworkPage.TOP', 'TOP').'</b></div>';
			$data = array(
				'MemberLink' => Controller::join_links($this->Link('member_detail'), $currentmemberid),
				'Member' => Distributor::get_obj_by_username($currentusername),
				'Image' => $this->RankImageURL($currentmemberrankcode)
			);
			$table .= $this->generate_node($data);
            $table .= '<p>.</p>';
			$table .= '<p><a class="view_tree" href="#" data-username="'.$parentusername.'"><span class="glyphicon glyphicon-chevron-up"></span></a></p>';
            $table .= '</td>';
            $table .= '</tr>';
        }
        for ($i = 0; $i < $showlevel; $i++) {
            $parentkey = 0;
            $arr_parentid = array();
            $arr_data_by_level = isset($searchResult[$i]) ? $searchResult[$i] : array();
            $colspan = $totalcol/$currentcol;
            $table .= '<tr class="team_level'.$i.'">';
            $currentparentid = 0;
			$currentposition = 0;
            for ($j = 1; $j <= $currentcol; $j++) {
                $arr_data = array();
                if($i == 0){
                    $arr_data = isset($arr_data_by_level[$parentid][$position]) ? $arr_data_by_level[$parentid][$position] : array();
                }
                else{
                	$currentposition += 1;
					
                    if(isset($arr_postparentid[$parentkey]) && $currentparentid = (int)$arr_postparentid[$parentkey]){
                        if(isset($arr_data_by_level[$currentparentid][$currentposition])){
                            $arr_data = $arr_data_by_level[$currentparentid][$currentposition];
                        }
                    }
                    
                    if($currentposition >= $child_limit){
                        $parentkey += 1;
                    }
                }
                if(sizeof($arr_data)){
                    $table .= '<td colspan="'.$colspan.'" class="text-center">';
					$data = array(
						'MemberLink' => Controller::join_links($this->Link('member_detail'), $arr_data['distributorid']),
						'Member' => Distributor::get_obj_by_username($arr_data['username']),
						'Image' => $this->RankImageURL($arr_data['rankcode'])
					);
					$table .= $this->generate_node($data);
					if($i+1 == $showlevel){
						$table .= '<br><a class="view_tree" href="#" data-username="'.$arr_data['username'].'"><span class="glyphicon glyphicon-chevron-down"></span></a>';
					}
                    $table .= "</td>";
                        
                    $arr_parentid[] = $arr_data['id'];
                }
                else{
                    $table .= '<td colspan="'.$colspan.'" class="text-center">';
                    if($currentparentid){
						$page = DataObject::get_one('RegistrationPage');
						$url = $page ? Controller::join_links($this->Link('placement_signup'), Distributor::get_username_by_id($currentparentid), $currentposition) : '';
						$data = array(
							'ParentID' => $currentparentid,
							'Link' => $url,
							'Image' => $this->RankImageURL('register')
						);
						$table .= $this->generate_node($data);
                    }
                    else{
                    	$data = array(
                    		'ParentID' => 0,
                    		'Link' => '',
							'Image' => $this->RankImageURL('empty')
						);
						$table .= $this->generate_node($data);
                    }

                    $table .= '</td>';
                    
                    $arr_parentid[] = 0;
                }

				if(!($j % $child_limit)){
                	$currentposition = 0;
				}
            }
            $table .= '</tr>';
            $currentcol *= $child_limit;
            $arr_postparentid = $arr_parentid;
        }
        $table .= '</tbody>';
        $table .= '</table>';
        $table .= '</div>';
        
        return Convert::array2json(array('result' => $table));
    }
    
	protected function generate_node($data){
		$template = new SSViewer('TeamNetworkPage_generate_node');
        $template->includeRequirements(false);
        return $template->process($this->customise($data));
	}
    
    function member_detail(){
        $current_placement = Placement::get()->find('MemberID', (int)Distributor::currentUserID());
        $placement = Placement::get()->filter('NLeft:GreaterThanOrEqual', $current_placement->NLeft)->filter('NRight:LessThanOrEqual', $current_placement->NRight)->find('MemberID', (int)$this->request->param('ID'));
        if($placement){
            $member = Member::get()->byID($placement->MemberID);
			
	        $template = new SSViewer('TeamNetworkPage_member_details');
	        $template->includeRequirements(false);
	        return $template->process($this->customise(array('Member' => $member, 'ShowSponsor' => Config::inst()->get('Sponsor', 'show_sponsor'))));
        }
        
        return _t('TeamNetworkPage.INVALID_MEMBER', 'Invalid member');
    }

	function placement_signup(){
		$page = DataObject::get_one('RegistrationPage');
		Session::set('SponsorUsername', $this->CurrentMember()->Username);
		Session::set('PlacementUsername', $this->request->param('ID'));
		Session::set('PlacementPosition', $this->request->param('OtherID'));
		return $this->redirect($page->Link());
	}

    function RankImageURL($rankcode){
        $theme_dir = sprintf('%s/images/placement/', SSViewer::get_theme_folder());
        $icon = $rankcode ? sprintf('%s_icon.png', strtolower($rankcode)) : 'unknow_icon.png';
        if(Director::fileExists($theme_dir.$icon)){
            return $theme_dir.$icon;
        }
		else if(Director::fileExists('network/images/placement/'.$icon)){
			return 'network/images/placement/'.$icon;
		}
		else{
			if(Director::fileExists($theme_dir.'unknow_icon.png')){
	            return $theme_dir.'unknow_icon.png';
	        }
			else {
				return 'network/images/placement/unknow_icon.png';
			}
		}
    }
}